﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Context;

namespace LogDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("请选择日志提供程序：");
            Console.WriteLine("1:自定义日志");
            Console.WriteLine("2:SeriLog");
            switch (Console.ReadKey().KeyChar)
            {
                case '1':
                    myLogger(args);
                    break;
                case '2':
                    seriLogger(args);
                    break;

            }
        }
        private static void seriLogger(string[] args)
        {
            var hostBuilder = Host.CreateDefaultBuilder(args);
            hostBuilder.ConfigureServices((hostBuilderContext, services) =>
            {
                services.AddHostedService<Job>();
                services.AddHostedService<Job1>();
            });

            //Log.Logger = new LoggerConfiguration()   //创建日志方式一，优势：可在Host启动前后记录日志，也可记录Host崩溃的日志
            //    .Enrich.FromLogContext()
            //    .ReadFrom.Configuration(new ConfigurationBuilder()
            //        .AddJsonFile("Serilog.json", true, true)
            //        .Build()
            //     )
            //    .CreateLogger();
            //hostBuilder.UseSerilog();

            hostBuilder.ConfigureAppConfiguration(configureBuilder =>
            {
                configureBuilder.AddJsonFile("Serilog.json", true, true);
            });
            hostBuilder.UseSerilog((hostBuilderContext, configureLogger) =>
            {
                configureLogger.ReadFrom.Configuration(hostBuilderContext.Configuration);
                configureLogger.Enrich.WithProperty("User", "匿名"); //在日志中写入自定义标签信息
                //通过以下语句可以在Web中通过LogContext.PushProperty("key","value")\logger.PushProperty\logger.BeginScope等在日志中通过{key}填充自定义信息，如当前登陆用户等
                //configureLogger.Enrich.FromLogContext();
            });

            var host = hostBuilder.Build();
            host.Run();

            Log.CloseAndFlush(); //异步日志时调用此方法回写所有未完成的日志,防止日志丢失
        }

        private static void myLogger(string[] args)
        {
            var hostBuilder = Host.CreateDefaultBuilder(args);
            hostBuilder.ConfigureLogging(loging =>
            {
                loging.AddProvider(new MyLoggerProvider());
            });
            hostBuilder.ConfigureServices(services =>
            {
                services.AddHostedService<Job>();
                services.AddHostedService<Job1>();
            });
            var host = hostBuilder.Build();
            host.Run();
        }
    }
}